﻿using HalconDotNet;
using Halcon二次开发.Controller.主界面交互;
using Halcon二次开发.Model;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.自定义控件;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace Halcon二次开发.View.工位监控画面
{
    public partial class MonitoringForm : Form
    {
        //默认工程存储路径
        private string probectPath = @"Data\工程文件\";
        //存储当前工位的MDI容器中子窗体的位置
        private Dictionary<string, string> windowPositions = new Dictionary<string, string>();
        private static Form1 form = null;
        private static HwindowFlowNodeUrseControl hwindowFlowNodeUrse1=null;
        /// <summary>
        /// 单例模式
        /// </summary>
        private MonitoringForm()
        {
            InitializeComponent();
            
            Display_Text();
        }
        /// <summary>
        /// 更新该工位的名称
        /// </summary>
        public void Display_Text() {
            try
            {
                this.toolStripMenuItem1.Text = (FormDb.Db["Form1"] as Form1).projectName;
            }
            catch { }
        }

        //所有实时监控画面的对象
        public List<FramesTimeForm> framesUserContorls = new List<FramesTimeForm>();

        private static MonitoringForm monitoringForm ;
        /// <summary>
        /// 单例模式设计
        /// </summary>
        /// <returns></returns>
        public static MonitoringForm GetMonitoringForm(Form1 form1=null)
        {
            if (form1!=null)
            {
                form=form1;
            }
            if (monitoringForm == null)
            {
                monitoringForm = new MonitoringForm();
            }
            return monitoringForm;
        }
        public static MonitoringForm GetMonitoringForm(HwindowFlowNodeUrseControl hwindowFlowNodeUrse)
        {
            if (hwindowFlowNodeUrse != null)
            {
                hwindowFlowNodeUrse1 = hwindowFlowNodeUrse;
            }
            if (monitoringForm == null)
            {
                monitoringForm = new MonitoringForm();
            }
            return monitoringForm;
        }
        /// 
        private void MonitoringForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            (FormDb.Db["Form1"] as Form1).CloseThread();
           (FormDb.Db["Form1"] as Form1).Savedata();
            (FormDb.Db["Form1"] as Form1).Close();

            try
            {
                SavePoint();
            }
            catch { }
        }
        public void SavePoint()
        {
            try
            {
                // 清空字典，重新保存窗体位置和大小
                windowPositions.Clear();

                // 获取当前MdiChildren的窗体，保存它们的名字、位置和大小
                string probjectName = "";
                // 获取当前MdiChildren的窗体，保存它们的名字、位置和大小
                bool paper = true;
                foreach (var child in this.MdiChildren)
                {
                    if (paper)
                    {
                        probjectName = ((FramesTimeForm)child).probjectName;
                        paper = false;
                    }
                    // 获取窗体位置并以“x,y”格式保存
                    var position = $"{child.Location.X},{child.Location.Y}";
                    var size = $"{child.Width},{child.Height}";  // 保存窗体的宽度和高度
                    windowPositions[child.Text] = position + "," + size; // 或者使用 Name 来唯一标识
                }

                // 使用StreamWriter保存窗体位置字典
                using (StreamWriter writer = new StreamWriter(probectPath + probjectName + "\\" + "mdiWindowPositions.txt"))
                {
                    foreach (var item in windowPositions)
                    {
                        writer.WriteLine($"{item.Key},{item.Value}");
                    }
                }
            }
            catch { }
        }
        /// <summary>
        /// 加工位画面加载到窗体上
        /// </summary>
        public void AddFramesTime(HwindowFlowNodeUrseControl hwindowFlowNodeUrse)
        {
            //string srts=hwindowFlowNodeUrse.name;
            //framesUserContorls.Add(new FramesTimeForm(hwindowFlowNodeUrse,this));
        }
        //横向排序窗体
        private void 横向排列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal); //使用MdiLayout枚举实现窗体的水平平铺
        }
        //纵向排序窗体
        public void 纵向排列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BtnGridArrange_Click(sender, e);
        }
        public void ToolStripHeng()
        {
          
            纵向排列ToolStripMenuItem_Click(null,null);
            
        }
        /// <summary>
        /// 获取当前实时监控对象
        /// </summary>
        /// <returns></returns>
        public FramesTimeForm GetHSmartWindow(string name)
        {
            int length = framesUserContorls.Count;
            foreach (FramesTimeForm item in framesUserContorls)
            {
                if (item.name.Equals(name))
                {
                    return item;
                }
            }
            return null;
        }
        /// <summary>
        ///  释放以删除的窗体
        /// </summary>
        public void DelForms(string name)
        {
            try
            {
                foreach (FramesTimeForm child in this.MdiChildren)
                {
                    if (child.name == name) // 替换为你要关闭的子窗体的名称
                    {
                        child.Close();
                        break; // 如果只需关闭一个，则找到后退出循环
                    }
                }
            }
            catch { }
        }

        public void DelSum() {
            try
            {
                foreach (FramesTimeForm child in this.MdiChildren)
                {
                    child.Close();
                }
            }
            catch { }
        }
        /// <summary>
        /// 切换工程时删除
        /// </summary>
        /// <param name="name"></param>
        public void VerifyDelProject(string name)
        {
            try
            {
                //清空MDI容器
                foreach (FramesTimeForm child in this.MdiChildren)
                {
                    if (child.Text == name) // 替换为你要关闭的子窗体的名称
                    {
                        child.Close();
                        break; // 如果只需关闭一个，则找到后退出循环
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 跳转主界面中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 参数设置窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //保存一下当前窗体的位置
            try
            {
                SavePoint();
            }
            catch { }
            if (form!=null)
            {
                form.Show();
                this.Hide();
            }
        }
        /// <summary>
        /// 启动时纵向排列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MonitoringForm_Load(object sender, EventArgs e)
        {
            //纵向排列ToolStripMenuItem_Click(sender, e);
            RestoreMDIWindowOrder();
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
           
        }
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            
        }

        private void 暂停所有工位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }
        private void BtnGridArrange_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取所有MDI子窗体
                int heights = this.ClientSize.Height;  // 使用 ClientSize 而不是 Height，避免标题栏影响
                int windowWidth = 851;  // 每个窗体的宽度
                int windowHeight = 484; // 每个窗体的高度
                int maxColumns = 2;     // 每行最多放2个窗体
                Form[] childForms = this.MdiChildren;
                int coutn = 0;

                // 当前窗体位置
                int point_x = 0;
                int point_y = 0;

                // 确保 MDI 子窗体的数量不小于 tabControl 中的选项卡数量
                for (int i = 0; i < form.tabControl2.TabPages.Count; i++)
                {
                    if (coutn == maxColumns) // 每行最多放2个窗体
                    {
                        coutn = 0;
                        point_x = 0;  // 下一行从左边开始
                        point_y += windowHeight;  // 移动到下一行
                    }

                    foreach (var item in childForms)
                    {
                        // 通过Tab页的Text匹配到对应的窗体
                        if (form.tabControl2.TabPages[i].Text == ((FramesTimeForm)item).name)
                        {
                            // 设置每个窗体的位置
                            item.Location = new System.Drawing.Point(point_x, point_y);

                            // 设置每个窗体的大小
                            item.Size = new System.Drawing.Size(windowWidth, windowHeight);

                            // 更新 x 位置，以便下一个窗体放在右边
                            point_x += windowWidth;

                            // 每行两个窗体，控制位置
                            coutn++;
                            break;  // 找到对应的窗体后跳出循环
                        }
                    }
                }
            }
            catch { }
        }
        /// <summary>
        /// 读取上一次窗体的位置开始排版
        /// </summary>
        public void RestoreMDIWindowOrder()
        {
            try
            {
                if (this.MdiChildren.Length > 0)
                {
                    string name = (this.MdiChildren[0] as FramesTimeForm).probjectName;
                    string paths = probectPath + name + "\\mdiWindowPositions.txt";
                    if (File.Exists(paths))
                    {
                        // 清空字典，准备加载数据
                        windowPositions.Clear();

                        // 读取保存的窗体位置和大小字典
                        using (StreamReader reader = new StreamReader(paths))
                        {
                            string line;
                            while ((line = reader.ReadLine()) != null)
                            {
                                var parts = line.Split(',');
                                if (parts.Length == 5)  // 位置+大小（x,y,width,height）
                                {
                                    // 解析窗体名称、位置和大小
                                    var windowName = parts[0];
                                    var position = parts[1] + "," + parts[2];
                                    var size = parts[3] + "," + parts[4];

                                    // 将位置和大小保存到字典
                                    windowPositions[windowName] = position + "," + size;
                                }
                            }
                        }

                        // 根据保存的顺序恢复窗体的位置和大小
                        foreach (var windowName in windowPositions.Keys)
                        {
                            var window = this.MdiChildren.FirstOrDefault(w => w.Text == windowName);
                            if (window != null)
                            {
                                // 获取保存的位置和大小
                                var positionAndSize = windowPositions[windowName].Split(',');
                                int x = int.Parse(positionAndSize[0]);
                                int y = int.Parse(positionAndSize[1]);
                                int width = int.Parse(positionAndSize[2]);
                                int height = int.Parse(positionAndSize[3]);

                                // 设置窗体的位置和大小
                                window.Location = new System.Drawing.Point(x, y);
                                window.Size = new System.Drawing.Size(width, height);
                            }
                        }
                    }
                }
            }
            catch { }

        }

        private void 启动所有工位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                form.PaperTrue();
                form.toolStripMenuItem3_Click(sender, e);
               // 参数设置窗口ToolStripMenuItem.Enabled = false;
            }
            catch
            {

            }
        }

        private void 清除所有计数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            form.toolStripMenuItem4_Click(sender, e);
        }

        private void 暂停所有工位ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            form.toolStripMenuItem5_Click( sender,  e);
            参数设置窗口ToolStripMenuItem.Enabled = true;
        }
    }
}